<template>
    <div class="lottery-box" v-loading="loading">
        <el-form :model="lotteryData" :rules="rules" ref="lotteryData" label-width="120px" class="demo-ruleForm">
            <!-- <div class="input-img-box">
                <el-form-item label="奖品图" required>
                    <uploadCutOwnImg v-model="lotteryData.rewardPic" :width="1080" :height="624"/>
                </el-form-item>
            </div> -->
            <el-form-item label="活动时效" prop="startTime" required>
                <el-date-picker
                    v-model="validBeginDate"
                    type="datetimerange"
                    :picker-options="pickerOptions"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    @change="dateChange">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="中奖率配置" prop="moudleId" required>
                <el-select @change="moduleChange" style="width:150px;" v-model="lotteryData.moudleId">
                    <el-option v-for="(item, index) in moduleList" :key="index" :label="item.name" :value="item.moudleId"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="最大奖项" prop="maxReward" required>
                <el-input v-model="lotteryData.maxReward" placeholder="最大奖项" type="input" style="width:150px"></el-input> (分享使用)
            </el-form-item>
            <el-form-item label="等级" prop="level" required>
                <el-input v-model="lotteryData.level" type="number" @input="levelChange" style="width:150px"></el-input> 目前只有1~3级有匹配颜色
            </el-form-item>
            <el-form-item label="背景色" prop="bgColor" required>
                <el-input v-model="lotteryData.bgColor" disabled type="input" style="width:150px"></el-input>
                <span class="colorspan" :style="{'background': `rgba(${lotteryData.bgColor})`}"></span>
            </el-form-item>
            <el-form-item label="卡片色" prop="cardColor" required>
                <el-input v-model="lotteryData.cardColor" disabled type="input" style="width:150px"></el-input>
                <span class="colorspan" :style="{'background': `rgba(${lotteryData.cardColor})`}"></span>
            </el-form-item>
            <el-form-item label="百分比色" prop="percentColor" required>
                <el-input v-model="lotteryData.percentColor" disabled type="input" style="width:150px"></el-input>
                <span class="colorspan" :style="{'background': `rgba(${lotteryData.percentColor})`}"></span>
            </el-form-item>
            <div v-for="(it, index) in lotteryData.luckyGameInfoList" :key="index">
                <el-form :model="it" :rules="rules" :ref="`lotteryData-${index}`" label-width="120px" class="demo-ruleForm">
                    <el-form-item :label="`关联游戏${index + 1}`" prop="gameName" required>
                        <selectGame :getGame="getGame" width="300px" :gameInfo="it" :gameIndex="index" />
                        <span class="el-icon-remove delGame" @click="delGame(index)" v-if="index > 0"></span>
                    </el-form-item>
                    <el-form-item label="对应标题" prop="title" required>
                        <el-input v-model="it.title" style="width:300px"></el-input>
                    </el-form-item>
                    <el-form-item label="对应副标题" prop="subtitle" required>
                        <el-input v-model="it.subtitle" autosize type="textarea" style="width:300px"></el-input>
                    </el-form-item>
                     <el-form-item label="奖品池说明" prop="rewardDesc" required>
                        <div :id="`editor-${index}`" style="width: 500px"></div>
                    </el-form-item>
                    <el-form-item label="详情banner" prop="banner" required>
                        <uploadCutOwnImg v-model="it.banner" :width="1080" :height="840"/>
                    </el-form-item>
                </el-form>
            </div>
            <el-form-item>
                <el-button type="primary" @click="addGame">添加关联游戏</el-button>
                <el-button type="primary" @click="submitForm">保存</el-button>
                <!-- <el-button type="primary" @click="cancelForm('pieceDate')">取消</el-button> -->
                <el-button type="primary" @click="submitForm('copy')">复制</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import { formatDate } from '@/utils/utils'
import E from 'wangeditor'
export default {
    data () {
        const validateColor = (rule, value, callback) => {
            let reg = /^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/
            if (reg.test(`rgb(${value})`)) {
                let v = value.split(',')
                v.map(item => {
                    if (item < 0 || item > 255) callback(new Error('请输入正确的颜色值'))
                })
                callback()
            } else {
                callback(new Error('请输入正确的颜色值'))
            }
        }
        return {
            lotteryData: {
                luckyGameInfoList: [],
                level: 1,
                startTime: '',
                endTime: '',
                maxReward: '',
                // subtitle: '',
                moudleId: '',
                bgColor: '',
                cardColor: '',
                percentColor: ''
                // rewardDesc: ''
            },
            moduleList: [],
            gameList: [],
            validBeginDate: [],
            pickerOptions: {
                disabledDate (time) {
                    return time.getTime() < Date.now() - 1000 * 60 * 60 * 24
                },
                selectableRange: '00:00:00 - 23:59:59'
            },
            colorList: [
                {
                    bgColor: '62,135,214',
                    percentColor: '104,177,255',
                    cardColor: '46,113,186'
                },
                {
                    bgColor: '76,62,214',
                    percentColor: '110,104,255',
                    cardColor: '56,46,186'
                },
                {
                    bgColor: '213,189,130',
                    percentColor: '248,220,150',
                    cardColor: '180,157,103'
                }
            ],
            loading: false,
            gameLoading: false,
            rules: {
                level: [
                    { required: true, message: '请输入等级', trigger: 'change' }
                ],
                subtitle: [
                    { required: true, message: '请填写奖品池说明', trigger: ['blur', 'change'] }
                ],
                gameName: [
                    { required: true, message: '请选择关联游戏', trigger: ['blur', 'change'] }
                ],
                title: [
                    { required: true, message: '请填写对应标题', trigger: ['blur', 'change'] }
                ],
                bgColor: [
                    { validator: validateColor, trigger: ['blur', 'change'] }
                ],
                cardColor: [
                    { validator: validateColor, trigger: ['blur', 'change'] }
                ],
                percentColor: [
                    { validator: validateColor, trigger: ['blur', 'change'] }
                ],
                rewardDesc: [
                    { required: true, message: '请输入奖品介绍', trigger: ['blur', 'change'] }
                ],
                moudleId: [
                    { required: true, message: '请选择抽奖模板', trigger: 'change' }
                ],
                startTime: [
                    { required: true, message: '请选择活动时效', trigger: ['blur', 'change'] }
                ],
                maxReward: [
                    { required: true, message: '请输入最大奖项', trigger: ['blur', 'change'] }
                ]
            }
        }
    },
    created () {
        this.pickerOptions.selectableRange = formatDate((+new Date() + 10 * 60 * 1000), 'HH:MM:SS') + ' - 23:59:59'
        this.lotteryData.activityId = this.$route.query.id || null
    },
    mounted () {
        if (this.lotteryData.activityId) {
            this.getDetail()
        } else {
            this.lotteryData.luckyGameInfoList.push({
                activityId: null,
                gameId: '',
                gameName: '',
                title: '',
                banner: '',
                rewardDesc: '',
                subtitle: ''
            })
            this.levelChange(1)
            this.$nextTick(() => {
                this.createEditor(0)
            })
        }
        this.getModule()
    },
    methods: {
        getDetail () { // 获取抽奖详情
            this.$http.post('/lottrey/selectLuckyActivityDetail', {
                activityId: this.lotteryData.activityId
            }).then(res => {
                if (res.code === '0') {
                    this.lotteryData = res.data
                    this.validBeginDate = [res.data.startTime, res.data.endTime]
                    this.lotteryData.startTime = formatDate(res.data.startTime, 'YYYY-MM-DD HH:MM:SS')
                    this.lotteryData.endTime = formatDate(res.data.endTime, 'YYYY-MM-DD HH:MM:SS')
                    this.$nextTick(() => {
                        this.lotteryData.luckyGameInfoList.map((item, index) => {
                            this.createEditor(index)
                        })
                    })
                } else {
                    this.$message({
                        type: 'error',
                        message: '系统异常，请稍后再试'
                    })
                }
            })
        },
        getModule () { // 获取模板列表
            this.$http.post('/lottrey/selectMoudle', {}).then(res => {
                if (res.code === '0') {
                    this.moduleList = res.data
                } else {
                    this.$message({
                        type: 'error',
                        message: '系统异常，请稍后再试'
                    })
                }
            })
        },
        submitForm (type) { // 提交表单
            if (this.validateForm()) {
                // if (!this.lotteryData.rewardPic) {
                //     return this.$message({
                //         type: 'error',
                //         message: '请选择奖品图'
                //     })
                // }
                let flag = false
                this.lotteryData.luckyGameInfoList.forEach(item => {
                    if (!item.banner) flag = true
                })
                if (flag) {
                    return this.$message({
                        type: 'error',
                        message: '请选择关联游戏banner'
                    })
                }
                let message
                let params = Object.assign({}, this.lotteryData)
                if (this.lotteryData.activityId) {
                    message = '保存成功'
                } else {
                    message = '创建成功'
                }
                if (type === 'copy') {
                    message = '复制成功'
                    params.activityId = ''
                    params.phase = ''
                    params.status = null
                    params.rewardStatus = null
                    params.currentTimes = null
                }
                this.$http.post('/lottrey/updateActivityInfo', params).then(res => {
                    if (res.code === '0') {
                        this.$message({
                            type: 'success',
                            message
                        })
                        if (!this.lotteryData.activityId || type === 'copy') {
                            setTimeout(() => {
                                this.$router.push('/lottery/lotteryInfo')
                            }, 1000)
                        }
                    } else {
                        this.$message({
                            type: 'error',
                            message: '系统异常，请稍后再试'
                        })
                    }
                })
            }
        },
        validateForm () {
            let flag = true
            this.$refs['lotteryData'].validate(valid => {
                if (!valid) {
                    flag = false
                }
            })
            for (let i in this.lotteryData.luckyGameInfoList) {
                this.$refs[`lotteryData-${i}`][0].validate(valid => {
                    if (!valid) {
                        flag = false
                    }
                })
            }
            return flag
        },
        dateChange (val) { // 活动时效时间修改
            if (!val) {
                this.lotteryData.startTime = ''
                this.lotteryData.endTime = ''
            } else {
                this.lotteryData.startTime = formatDate(val[0].getTime(), 'YYYY-MM-DD HH:MM:SS')
                this.lotteryData.endTime = formatDate(val[1].getTime(), 'YYYY-MM-DD HH:MM:SS')
            }
        },
        moduleChange (item) { // 选择模板
            this.lotteryData.moudleId = item
        },
        levelChange (item) {
            if (item < 4 && item > 0) {
                this.lotteryData.bgColor = this.colorList[item - 1].bgColor
                this.lotteryData.percentColor = this.colorList[item - 1].percentColor
                this.lotteryData.cardColor = this.colorList[item - 1].cardColor
            }
        },
        addGame () {
            let relevanceList = {
                activityId: this.lotteryData.activityId,
                banner: '',
                gameId: '',
                gameName: '',
                title: ''
            }
            this.lotteryData.luckyGameInfoList.push(relevanceList)
            this.$nextTick(() => {
                this.createEditor(this.lotteryData.luckyGameInfoList.length - 1)
            })
        },
        delGame (index) {
            this.lotteryData.luckyGameInfoList.splice(index, 1)
        },
        getGame (val, index) {
            this.lotteryData.luckyGameInfoList[index] = Object.assign(this.lotteryData.luckyGameInfoList[index], val)
        },
        // 初始化富文本编辑器
        createEditor (index) {
            this.editor = new E(`#editor-${index}`)
            this.editor.customConfig.uploadImgServer = '/admin/file/uploadPic'
            this.editor.customConfig.uploadImgParams = {
                needTransform: 1
            }
            this.editor.customConfig.uploadFileName = 'file'
            this.editor.customConfig.uploadImgHooks = {
                before: function (xhr, editor, files) {
                // 图片上传之前触发
                // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，files 是选择的图片文件
                // 如果返回的结果是 {prevent: true, msg: 'xxxx'} 则表示用户放弃上传
                // return {
                //     prevent: true,
                //     msg: '放弃上传'
                // }
                },
                success: function (xhr, editor, result) {
                // 图片上传并返回结果，图片插入成功之后触发
                // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
                },
                fail: function (xhr, editor, result) {
                // 图片上传并返回结果，但图片插入错误时触发
                // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
                },
                error: function (xhr, editor) {
                // 图片上传出错时触发
                // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
                },
                timeout: function (xhr, editor) {
                // 图片上传超时时触发
                // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
                },

                // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
                // （但是，服务器端返回的必须是一个 JSON 格式字符串！！！否则会报错）
                customInsert: function (insertImg, result, editor) {
                // 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
                // insertImg 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果

                    // 举例：假如上传图片成功后，服务器端返回的是 {url:'....'} 这种格式，即可这样插入图片：
                    var url = result.data
                    insertImg(url)

                // result 必须是一个 JSON 格式字符串！！！否则报错
                }
            }
            this.editor.customConfig.zIndex = 100
            this.editor.customConfig.menus = [
                // 'head', // 标题
                'bold', // 粗体
                // 'fontSize', // 字号
                // 'fontName', // 字体
                'italic', // 斜体
                'underline', // 下划线
                'strikeThrough', // 删除线
                'foreColor', // 文字颜色
                'backColor', // 背景颜色
                'link', // 插入链接
                // 'list', // 列表
                'justify', // 对齐方式
                // 'quote', // 引用
                // 'emoticon', // 表情
                'image', // 插入图片
                // 'table', // 表格
                // 'video', // 插入视频
                // 'code', // 插入代码
                'undo', // 撤销
                'redo' // 重复
            ]
            this.editor.customConfig.onchange = (html) => {
                this.lotteryData.luckyGameInfoList[index].rewardDesc = html
            }
            this.editor.create()
            this.editor.txt.html(this.lotteryData.luckyGameInfoList[index].rewardDesc)
        }
    }
}
</script>

<style>
    .lottery-box {
        max-width: 800px;
    }
    .delGame {
        margin-left: 10px;
        cursor: pointer;
    }
    .colorspan {
        display: inline-block;
        width: 10px;
        height: 16px;
        margin-left: 2px;
    }
</style>
